<?php
/**
 * Plugin Name: JamNews
 * Plugin URI: http://strawberry-jam.vn/jamnews
 * Description: Automatic setup News Post Type - News Funcion to template.
 * Version: 1.0.2
 * Author: Huy Jam & Vo Anh Kiet
 * Author URI: http://strawberry-jam.vn
 */ 

 if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
 if ( ! class_exists( 'Jamnews' ) ) {
/**
 * Main JamNews Class
 *
 * Contains the main functions for JamNews, stores variables, and handles error messages
 *
 * @class Jamnews
 * @package	JamNews
 * @author VoAnhKiet
 */
 
 class Jamnews{
	/**
	 * @var string
	 */
	public $version = '1.0.2';
	
	/**
	 * @var string
	 */
	public $plugin_remote_path = 'http://sh01.strawberry-jam.vn/plugins/jamnews/update.php';
	
	/**
	 * @var string
	 */
	public $table_name;
	/**
	 * @var string
	 */
	public $plugin_url;

	/**
	 * @var string
	 */
	public $plugin_path;
	
	/**
	 * JamNews Constructor.
	 *
	 * @access public
	 * @return void
	 */
	public function __construct() {
	
		// Define version constant
		define( 'JAMNEWS_VERSION', $this->version );
		
		// Installation
		register_activation_hook( __FILE__, array( $this, 'activate' ) );
		global $wpdb;	
		$this->table_name = $wpdb->prefix.'jamnews';
		
		// Updates
		add_action( 'admin_init', array( $this, 'update' ), 5 );
		
		// Include required files
		$this->includes();
		
		// Hooks
		add_action( 'init', array( $this, 'init' ), 0 );
		add_filter( 'editable_roles', array(&$this, 'editable_roles'));
		add_filter( 'map_meta_cap', array(&$this, 'map_meta_cap'),10,4);
	}
	
	/**
	 * update function.
	 *
	 * @access public
	 * @return void
	 */
	 public function update() {
		global $wpdb;
		if ( ! defined( 'IFRAME_REQUEST' ) && ( get_option( 'jamnews_version' ) != $this->version || get_option( 'jamnews_db_version' ) != $this->version ) ){
			$this->install();
		}
	}
	
	/**
	 * activate function.
	 *
	 * @access public
	 * @return void
	 */
	public function activate() {
		$this->install();
	}
	
	/**
	 * upgrade function.
	 *
	 * @access public
	 * @return void
	 */
	function install() {
		include_once( 'admin/jamnews-admin-install.php' );
		set_transient( '_jamnews_activation_redirect', 1, 60 * 60 );
		do_install_jamnews();
	}
	
	/**
	 * Insert option into table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_insert_option($args){
		global $wpdb;
		if(is_string($args)){
			 parse_str($args, $args);
		}
		if(isset($args['meta_value'])){
			$args['meta_value'] = serialize($args['meta_value']);
		}
		$result = $wpdb->insert($this->table_name,$args);
		return ($result)?$wpdb->insert_id:$result;
	}
	
	/**
	 * Update option into table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_update_option($args){
		global $wpdb;
		$data_update = array();
		$args = (object)$args;
		foreach( $args as $key => $value ){
			if( $key == 'id' ) continue;
			$data_update[$key] = ($key=='meta_value')?serialize($value):$value;
		}
		
		return $wpdb->update($this->table_name,$data_update,array('id'=>$args->id) );
	}
	
	/**
	 * Delete option from table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_delete_option($field, $value){
		global $wpdb;
		return $wpdb->query( "DELETE FROM {$this->table_name} WHERE $field = '$value'");
	}
	
	/**
	 * Get options from table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_get_options( $where=''){
		global $wpdb;
		$str_query = "SELECT * FROM {$this->table_name}";
		
		if($where!=''){
				$str_query.=" WHERE $where";
		};
		return $wpdb->get_results($str_query);
	}
	
	/**
	 * Get post type from table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_get_post_types( $status='all', $fields = 'all' ){
		global $wpdb;
		if($status=='all'){
			$results = $this->db_get_options("namespace='post_type'");
		}elseif($status=='deactive'){
			$results = $this->db_get_options("namespace='post_type' AND status = '0'");
		}elseif($status=='active'){
			$results = $this->db_get_options("namespace='post_type' AND status = '1'");
		}
		
		foreach($results as $key => $oject){
			$results[$key]->meta_value = unserialize($results[$key]->meta_value);
		}
		
		switch($fields){
			case 'keys' :
				$_results = array();
				foreach($results as $key => $value){
					$_results[$value->meta_key] = $value->meta_key;
				}
				$results = $_results;
				break;
		}
		return $results;
	}
	
	/**
	 * Get a post type from table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_get_post_type($id){
		global $wpdb;
		list($data) = $this->db_get_options("id={$id}");
		$data->meta_value = unserialize($data->meta_value);
		return $data;
	}
	
	/**
	 * Get taxonomy from table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_get_taxonomy( $status='all' ){
		global $wpdb;
		if($status=='all'){
			$results = $this->db_get_options("namespace='taxonomy'");
		}elseif($status=='deactive'){
			$results = $this->db_get_options("namespace='taxonomy' AND status = '0'");
		}elseif($status=='active'){
			$results = $this->db_get_options("namespace='taxonomy' AND status = '1'");
		}
		foreach($results as $key => $oject){
			$results[$key]->meta_value = unserialize($results[$key]->meta_value);
		}
		return $results;
	}
	
	/**
	 * Active rows from table jamnews
	 *
	 * @access public
	 * @return void
	 */
	function db_active_rows( $ids, $active=true ){
		global $wpdb;
		if(!is_array($ids)){
			$results = $this->db_get_options("id='$id'");
		}else if(is_array($ids)){
			$results = $this->db_get_options("id='".implode("' OR id='",$ids)."'");
		}
		foreach($results as $key => $object){
			$object->meta_value = unserialize($object->meta_value);
			$object->status = $active?1:0;
			$this->db_update_option($object);
		}
		return $results;
	}
	
	/**
	 * Include required core files used in admin and on the frontend.
	 *
	 * @access public
	 * @return void
	 */
	function includes() {
		if ( is_admin() )
			$this->admin_includes();
		if ( defined('DOING_AJAX') )
			$this->ajax_includes();
		if ( ! is_admin() || defined('DOING_AJAX') )
			$this->frontend_includes();
	}
	
	/**
	 * Include required admin files.
	 *
	 * @access public
	 * @return void
	 */
	public function admin_includes() {
		include_once( 'admin/jamnews-admin-init.php' );			// Admin section
	}
	
	/**
	 * Include required ajax files.
	 *
	 * @access public
	 * @return void
	 */
	public function ajax_includes() {
		include_once( 'jamnews-ajax.php' );			// Ajax functions for admin and the front-end
	}
	
	/**
	 * Include required frontend files.
	 *
	 * @access public
	 * @return void
	 */
	public function frontend_includes() {
		include_once( 'jamnews-function.php' );
	}
	
	/** Helper functions ******************************************************/

	/**
	 * Get the plugin url.
	 *
	 * @access public
	 * @return string
	 */
	public function plugin_url() {
		if ( $this->plugin_url ) return $this->plugin_url;
		return $this->plugin_url = untrailingslashit( plugins_url( '/', __FILE__ ) );
	}

	/**
	 * Get the plugin path.
	 *
	 * @access public
	 * @return string
	 */
	public function plugin_path() {
		if ( $this->plugin_path ) return $this->plugin_path;

		return $this->plugin_path = untrailingslashit( plugin_dir_path( __FILE__ ) );
	}

	/**
	 * Get Ajax URL.
	 *
	 * @access public
	 * @return string
	 */
	public function ajax_url() {
		return admin_url( 'admin-ajax.php', 'relative' );
	}
	
	/**
	 * Init Jamnews when WordPress Initialises.
	 *
	 * @access public
	 * @return void
	 */
	public function init() {
		//Before init action
		do_action( 'before_jamnews_init' );

		// Set up localisation
		$this->load_plugintextdomain();
		
		// Load auto update
		$this->check_update_plugin();
		
		// Init action
		do_action( 'jamnews_init' );
	}
	
	/**
	 * Load auto update plugin
	 */
	function check_update_plugin() {
		require_once ('classes/wp_autoupdate.php');
		new wp_auto_update ($this->version, $this->plugin_remote_path, plugin_basename(__FILE__));
	}
	
	/**
	 * Load Localisation files.
	 *
	 * Note: the first-loaded translation file overrides any following ones if the same translation is present
	 *
	 * @access public
	 * @return void
	 */
	public function load_plugintextdomain() {
		
		$locale = apply_filters( 'plugin_locale', get_locale(), 'jamnews' );
		$formal = 'yes' == get_option( 'jamnews_informal_localisation_type' ) ? 'informal' : 'formal';
		load_textdomain( 'jamnews', WP_LANG_DIR . "/jamnews/jamnews-$locale.mo" );

		// Load admin specific MO files
		if ( is_admin() ) {
			load_textdomain( 'jamnews', WP_LANG_DIR . "/jamnews/jamnews-admin-$locale.mo" );
			load_textdomain( 'jamnews', $this->plugin_path() . "/languages/jamnews-admin-$locale.mo" );
		}
		if(function_exists('load_plugin_textdomain')){
			load_plugin_textdomain( 'jamnews', false, dirname( plugin_basename( __FILE__ ) ) . "/languages/$formal" );
			load_plugin_textdomain( 'jamnews', false, dirname( plugin_basename( __FILE__ ) ) . "/languages" );
		}
	}
	
	
	/**
	 * Get string to translate.
	 *
	 * @access public
	 * @return void
	 */
	function get_string_translate(){
		require_once($this->plugin_path."/languages/string.php");
		return get_string();
	}
	/**
	 * Remove 'Administrator' from the list of roles if the current user is not an admin
	 * 
	 * @access public
	 * @return void
	 */
	function editable_roles( $roles ){
		if( isset( $roles['administrator'] ) && !current_user_can('administrator') ){
			unset( $roles['administrator']);
		}
		return $roles;
	}

	/**
	 * If someone is trying to edit or delete and admin and that user isn't an admin, don't allow it
	 *
	 * @access public
	 * @return void
	 */
	  function map_meta_cap( $caps, $cap, $user_id, $args ){
		switch( $cap ){
			case 'edit_user':
			case 'remove_user':
			case 'promote_user':
				if( isset($args[0]) && $args[0] == $user_id )
					break;
				elseif( !isset($args[0]) )
					$caps[] = 'do_not_allow';
				$other = new WP_User( absint($args[0]) );
				if( $other->has_cap( 'administrator' ) ){
					if(!current_user_can('administrator')){
						$caps[] = 'do_not_allow';
					}
				}
				break;
			case 'delete_user':
			case 'delete_users':
				if( !isset($args[0]) )
					break;
				$other = new WP_User( absint($args[0]) );
				if( $other->has_cap( 'administrator' ) ){
					if(!current_user_can('administrator')){
						$caps[] = 'do_not_allow';
					}
				}
				break;
			default:
				break;
		}
		return $caps;
	}
}

 
/**
 * Init Jamnews class
 */
 $GLOBALS['jamnews'] = new Jamnews();
 
 }// class_exists check
?>